import Vue from 'vue'
import Alert from './alert.vue'
import pageScroll from '../../../_common/js/utils/pageScroll'

Alert.new = (options = {}) => {
  const instance = new Vue({
    data: options,
    render (h) {
      return h(Alert, {
        props: options
      })
    }
  })
  const component = instance.$mount()
  document.body.appendChild(component.$el)
  pageScroll.lock(component.$el)

  const alert = instance.$children[0]
  function hashChange () {
    pageScroll.unlock()
    const el = alert.$el
    el.parentNode && el.parentNode.removeChild(el)
  }
  window.addEventListener('hashchange', hashChange)

  alert.closeAlert = () => {
    const el = alert.$el
    pageScroll.unlock(el)
    el.parentNode && el.parentNode.removeChild(el)
    window.removeEventListener('hashchange', hashChange)
    typeof alert.callback === 'function' && alert.callback()
  }
}

export default Alert
